package com.mic.endpoint.api;


import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.api.server.spi.IoUtil;
import com.google.api.server.spi.ServiceContext;
import com.google.api.server.spi.config.annotationreader.ApiConfig.Factory;
import com.google.api.server.spi.tools.AnnotationApiConfigGenerator;
import com.google.api.server.spi.tools.ApiConfigGenerator;


public class EndpointApiGenerator {

    protected Map<String, String> generateApiConfigs(String applicationId, String classPath,
            List<String> serviceClassNames) throws Exception {
        ClassLoader classLoader = new URLClassLoader(toUrls(classPath), this.getClass().getClassLoader());
        Factory configFactory = new Factory();
        ApiConfigGenerator generator = new AnnotationApiConfigGenerator(classLoader, configFactory);
        return generator.generateConfig(ServiceContext.create(applicationId, "mic"),
                loadClasses(classLoader, serviceClassNames));
    }

    protected void write(Map<String, String> apiConfigs, String outputDirPath) throws Exception {
        File outputDir = new File(outputDirPath);
        String apiConfigFilePaths[] = new String[apiConfigs.size()];
        String apiConfigFilePath;
        int i = 0;
        for (Iterator<Map.Entry<String, String>> i$ = apiConfigs.entrySet().iterator(); i$.hasNext();) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) i$.next();
            apiConfigFilePath =
                    (new StringBuilder()).append(outputDir).append("/").append((String) entry.getKey()).toString();
            apiConfigFilePaths[i++] = apiConfigFilePath;
            IoUtil.writeFile(apiConfigFilePath, (String) entry.getValue());
        }
    }

    private static URL[] toUrls(String classPath) throws MalformedURLException {
        String paths[] = classPath.split(File.pathSeparator);
        URL urls[] = new URL[paths.length];
        for (int i = 0; i < paths.length; i++) {
            urls[i] = (new File(paths[i])).toURI().toURL();
        }
        return urls;
    }

    @SuppressWarnings("rawtypes")
    private static Class[] loadClasses(ClassLoader classLoader, List<String> classNames) throws ClassNotFoundException {
        Class classes[] = new Class[classNames.size()];
        for (int i = 0; i < classNames.size(); i++) {
            classes[i] = classLoader.loadClass((String) classNames.get(i));
        }
        return classes;
    }
}
